<?php
/**
 * @author Jumper Swordwave
 * date: 2021/04/19
 */
namespace App\Controller;

use Hyperf\Contract\{OnOpenInterface, OnCloseInterface, OnMessageInterface};
use Swoole\WebSocket\Frame;
use Swoole\Http\Request;

use App\Constants\ErrorCode;
use App\Game\Core\{Dispatch, Command, Packet};
use App\Game\Core\Request as GameRequest;
use App\Log;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    private $dispatch;

    public function __construct(Dispatch $dispatch)
    {
        $this->dispatch = $dispatch;
    }

    public function onMessage($server, $frame) : void 
    {
        Log::info('onmessage');
        $data = Packet::decode($frame->data);
        Log::info(json_encode($data));
        if (!isset($data['code']) && $data['code'] != ErrorCode::SUCCESS) {
            Log::info('data error');
            Log::info($data);
            return;
        }
        $request = GameRequest::parser($frame->fd, $data);
        Log::info('websocket request', $request->toArray());
        $response = $this->dispatch->execute($request);
        if ($response != null) {
            $server->push($frame->fd, Packet::encode($response->getResult()), WEBSOCKET_OPCODE_BINARY);
        }
    }

    public function onClose($server, int $fd, int $reactorId) : void 
    {
        /*$request = Request::parser([
            'code' => ErrorCode::SUCCESS,
            'command' => Command::SYS_LOGOUT,
            'data' => [],
        ]);
        $response = $this->dispatch->execute($request);
        if ($response != null) {
            $server->push($fd, Packet::encode($response->getResult()), WEBSOCKET_OPCODE_BINARY);
        }*/
    }

    public function onOpen($server, $request) : void 
    {
        $game_req = GameRequest::parser($request->fd, [
            'code' => ErrorCode::SUCCESS,
            'command' => Command::SYS_CONNECTED,
            'message' => '',
            'user' => null,
            'data' => [],
        ]);
        $response = $this->dispatch->execute($game_req);
        if ($response != null) {
            $server->push($request->fd, Packet::encode($response->getResult()), WEBSOCKET_OPCODE_BINARY);
        }
    }
}